import React from 'react';
import { fetchFavoriteArticle } from '../actions/article';
import { connect } from 'react-redux';
import Articles from '../components/articles';
import Loadmore from '../components/loadmore';
import { Link } from 'react-router';
import NormalHeaderBar from '../components/NormalHeaderBar';

class FavoritePage extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.fetchFavoriteArticle(1, null);
    }

    handleLoad(page) {
        let key = this.refs.key.value;
        this.props.fetchFavoriteArticle(page,key);
        window.scrollTo(0,0);
    }

    searchByKey(e) {
        if (e.keyCode == 13) {
            this.searchByBtn();
        }
    }

    searchByBtn() {
        let key = this.refs.key.value;
        this.props.fetchFavoriteArticle(1,key);
    }

    render() {
        let articles = [];
        let articleDiv = (<div></div>);
        if (this.props.articles !== undefined && this.props.articles.length > 0) {
            articles = this.props.articles;
            articleDiv = (<Articles articles={articles}/>)
        } 
        let title = "我的关注";
        if (sessionStorage.nickname != undefined && sessionStorage.nickname != "undefined") {
            title = sessionStorage.nickname + " 的关注";
        }
        return (
            <div>
                <NormalHeaderBar title={title} img={sessionStorage.headimgurl}/>
                <div style={{height: "2.5rem",backgroundColor: "rgba(0, 0, 0, 0.05)",padding: "0.3rem"}}>
                    <form onSubmit={(e)=>{e.preventDefault();return false;}} action="">
                        <input onKeyDown={(e) => {this.searchByKey(e)}} ref="key" placeholder="搜索关键字" style={{outline:"none",border:"1px solid #e6e6e6",width: "100%",paddingLeft:"0.5rem",height: "1.8rem",borderRadius: "5px"}}></input>
                        <i onClick={this.searchByBtn.bind(this)} className="fa fa-search" aria-hidden="true" style={{position: "absolute",zIndex: "999",right: "0.0rem",width: "1.8rem",height: "1.8rem",fontSize: "1.2rem",marginTop: "0.3rem"}}></i>
                    </form>
                </div>
                { articleDiv }
                { articles.length > 0 && <Loadmore page={this.props.page} defaultPageSize={articles.length} pageCount={(articles.length * this.props.pageCount)} handleLoad={this.handleLoad.bind(this)} pageChange={this.handleLoad.bind(this)}/>}
            </div>
        )
    }
}

function mapStateToProps(state){
    return { 
        articles: state.favorite.articles,
        page: state.favorite.page,
        pageCount: state.favorite.pageCount,
    };
}

export default connect(mapStateToProps, { fetchFavoriteArticle })(FavoritePage);